<template>
  <div class="user-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="dialogVisible=true" :dialogType='add'>添加用户</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="用户类型">
          <el-select v-model="searchForm.role" 
                     style="width: 100px" 
                     :popper-append-to-body="true"
                     placeholder="请选择用户类型" 
                     @change="handleSearch">
            <el-option label="全部" value="all" />
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.realName"
            placeholder="姓名/学号/工号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="idNumber" label="学号/工号" width="130" />
        <el-table-column prop="realName" label="姓名" width="130" />
        <el-table-column prop="role" label="类型" width="130">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ userRoleMap[scope.row.role] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" width="200" />
        <el-table-column prop="status" label="状态" width="200">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ userStatusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="userFormData(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                :type="scope.row.status === 1 ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(scope.row)"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleResetPassword(scope.row)"
              >
                重置密码
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteUser(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="50%"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户类型" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>

        <el-form-item :label="userForm.role === 'student' ? '学号' : '工号'" prop="idNumber">
          <el-input v-model="userForm.idNumber" :disabled="dialogType === 'edit'" />
        </el-form-item>

        <el-form-item label="姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>

        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibles">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleAddUser">
            {{ loading ? (dialogType === 'add' ? '添加中...' : '保存中...') : (dialogType === 'add' ? '添加' : '保存') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref ,onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addUser,getUserList,resetPassword,updateUser } from '@/api/user'

// 添加 loading 状态
const loading = ref(false)

// 用户角色映射
const userRoleMap = {
  admin: '管理员',
  teacher: '教师',
  student: '学生'
}

// 用户状态映射
const userStatusMap = {
  1: '正常',
  0: '禁用'
}

// 搜索表单
const searchForm = ref({
  role: 'all',
  realName: '',
  idNumber: '',
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 用户列表数据
const userList = ref([
  {
    idNumber: 'admin001',
    realName: '管理员',
    role: 'admin',
    email: 'admin@example.com',
    phone: '13800138000',
    status: 'active'
  },
  {
    idNumber: 'teacher001',
    realName: '张老师',
    role: 'teacher',
    email: 'teacher@example.com',
    phone: '13800138001',
    status: 'active'
  },
  {
    idNumber: '2024001',
    realName: '李同学',
    role: 'student',
    email: 'student@example.com',
    phone: '13800138002',
    status: 'active'
  }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
// 添加表单引用
const userFormRef = ref(null)
const userForm = ref({
  role: '',
  idNumber: '',
  realName: '',
  email: '',
  phone: '',
  password: ''
})

const dialogVisibles = () => {
  dialogVisible.value = false
  userForm.value = {
    role: '',
    idNumber: '',
    realName: '',
    email: '',
    phone: '',
    password: ''
  }
  userFormRef.value?.resetFields()
}

const rules = {
  role: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' },
    { pattern: /^[0-9]{6,12}$/, message: '学号/工号必须为6-12位数字', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '姓名必须为2-10个汉字', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
  { required: false, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    { max: 20, message: '密码长度不能大于20位', trigger: 'blur' }
  ]
}

// 用户类型来取决哪种颜色
const getRoleType = (role) => {
  const typeMap = {
    admin: 'danger',
    teacher: 'warning',
    student: 'success'
  }
  return typeMap[role]
}

const handleSearch = () => {
  // 如果清空选择，默认设置为 "all"
  if (!searchForm.value.role) {
    searchForm.value.role = 'all'
  }
  // 实现搜索逻辑
  currentPage.value = 1  // 重置到第一页
  getUsersList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value={
    role: 'all',  // 重置为全部
    realName: '',
    idNumber: '',
  }
  handleSearch()
}


//查询用户列表
const getUsersList = async () => {
  try {
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      role: searchForm.value.role==='all' ? '' : searchForm.value.role,   // 如果是 "all" 就传空值
      realName: searchForm.value.realName,  // 使用 realName 作为搜索关键词
      idNumber: searchForm.value.realName  // 同时用于 idNumber 搜索
    }
    const res = await getUserList(params)
    if(res.code==200){
      userList.value = res.data.records
      total.value = res.data.total
      pageSize.value = res.data.pageSize
      currentPage.value = res.data.currentPage
    }else{
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}



// 添加用户
const handleAddUser = async () => {
  try {
    loading.value = true  // 开始加载
    await userFormRef.value.validate()
    // 根据 dialogType 判断是添加还是编辑
    if (dialogType.value === 'add') {
      const res = await addUser(userForm.value)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        getUsersList()
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    } 
    if(dialogType.value === 'edit'){
      const res = await updateUser(userForm.value)
      console.log(userForm.value);
      console.log(res);
      if(res.code===200){
        ElMessage.success('编辑成功')
        dialogVisible.value = false
        getUsersList()
      }else{
        ElMessage.error(res.message || '编辑失败')
      }
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败')
  } finally {
    loading.value = false  // 结束加载
  }
}

// 复制用户数据到表单
const userFormData = async (user) => {
  dialogType.value = 'edit'
    userForm.value = {
    role: user.role,
    idNumber: user.idNumber,
    realName: user.realName,
    email: user.email,
    phone: user.phone
  }
  dialogVisible.value = true
}

// 编辑用户
// const handleEditUser = async () => {
//   // dialogType.value = 'edit'
//   console.log(userForm.value);
// const res = await updateUser(userForm.value)
//       console.log(userForm.value);
//       console.log(res);
//       if (res.code === 200) {
//         ElMessage.success('修改成功')
//         dialogVisible.value = false
//         getUsersList()
//       } else {
//         ElMessage.error(res.message || '修改失败')
//       }
// }

// 切换用户状态
const handleToggleStatus = (user) => {
  const action = user.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实现状态切换逻辑
    ElMessage.success(`${action}成功`)
    getUsersList()
  }).catch(() => {})
}

// 重置密码
const handleResetPassword = async (data) => {
  ElMessageBox.confirm(
    '确定要重置该用户的密码吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          loading.value = true
          instance.confirmButtonLoading = true
          try {
            const params = {
              idNumber: data.idNumber 
            }
            const res = await resetPassword(params)
            console.log(res);
            if (res.code === 200) {
              ElMessage.success('密码重置成功')
              done()
            } else {
              ElMessage.error(res.message || '密码重置失败')
            }
          } catch (error) {
            console.log(error);
          } finally {
            loading.value = false
            instance.confirmButtonLoading = false
            done() // 确保在所有情况下都调用 done()
          }
        } else {
          done()
        }
      }
    }
  )
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
  getUsersList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
  getUsersList()
}

onMounted(() => {
  getUsersList()
})
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 